import {ref, onMounted,watch} from "vue"
import {Base64 as bianma} from "js-base64"
import Cookies from 'js-cookie'
// 是否支持localStorage
let isSupport = null
// 判断是不是支持
const panduan = () => {
    isSupport = !!window.localStorage;
}

function uselocalStorage(name,value=null) {
    const data = ref(null)
    // 初始化的时候从localStorage里面获取对应的数据
    const init = () => {
        if (isSupport) {
            const shuju = localStorage.getItem(name)
            if (shuju) {
                data.value = JSON.parse(bianma.decode(shuju))
            } else {
                data.value = value
            }
        } else {
            const shuju = Cookies.get(name)
            if(shuju){
                data.value = JSON.parse(bianma.decode(shuju))
            }else{
                data.value = value;
            }
        }
    }
    // 监听区域,开启深度监听
    watch(data,()=>{
        // console.log("监听到一次变化，保存它",data)
        if(isSupport){
            if(data.value===null || data.value===undefined){
                localStorage.removeItem(name);
            }else{
                localStorage.setItem(name,bianma.encode(JSON.stringify(data.value)))
            }
        }else{
            if(data.value===null || data.value===undefined){
                Cookies.remove(name);
            }else{
                Cookies.set(name,bianma.encode(JSON.stringify(data.value)))
            }
        }
    },{deep:true})
    // 如果判断是空字符串，说明没有判断，先进行判断
    if (isSupport === null) {
        panduan()
    }
    // 首先读取存放的数据
    init()
    return data
}

export default uselocalStorage